package com.xiaocikuai.smallchunks.controller.aichat;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaocikuai.smallchunks.entity.AIChat.TtsRequest;
import com.xiaocikuai.smallchunks.entity.Advertise.ImgUni;
import com.xiaocikuai.smallchunks.utils.resultd.Resultd;

import okhttp3.*;
import okhttp3.RequestBody;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Base64;

@RestController
@RequestMapping("/api/aichat")
@CrossOrigin
public class AIChat {
    public static final String HOST = "openspeech.bytedance.com";
    public static final String API_URL = "https://" + HOST + "/api/v1/tts";
    public static final String ACCESS_TOKEN = "x9vtY_G_xY7Z9FjH61sqKQSCqx76yezR";



    public static String post(String url, String json) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .header("Authorization", "Bearer; " + ACCESS_TOKEN)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String jsonResponse = response.body().string();
            int dataIndex = jsonResponse.indexOf("\"data\":\"") + "\"data\":\"".length();
           return  jsonResponse.substring(dataIndex, jsonResponse.indexOf("\"", dataIndex));
        }
    }

    @PostMapping("/getchat")
    public Resultd AddAdvertise(@RequestHeader("Authorization") String token, @org.springframework.web.bind.annotation.RequestBody ImgUni text){
        TtsRequest ttsRequest = new TtsRequest(text.getImg());
        try {
            System.out.println("1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
            System.out.println(ttsRequest.getAudio().getSpeedRatio());
            return Resultd.ok().data("info", (post(API_URL, JSON.toJSONString(ttsRequest))));
        } catch (IOException e) {
            // 在这里处理异常情况，例如返回错误信息
            return Resultd.error().data("info", "与服务器通信时发生错误: " + e.getMessage());
        }
    }



}
